package com.zrrd.yt.mq.controller;

import com.zrrd.yt.common.result.Result;
import com.zrrd.yt.mq.config.DelayedMqConfig;
import com.zrrd.yt.rabbit.service.RabbitService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author HongyueYang
 */
@RestController
@RequestMapping("/mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //发送消息
    @GetMapping("/sendMessage")
    public Result sendMessage(){
        rabbitService.sendMessage("exchange.yt","routing.yt", "hello");
        return Result.ok();
    }

    //发送延迟消息
    @GetMapping("/sendDelayMessage")
    public Result sendDelayMessage(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, "这是一条延迟消息",
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        //设置延迟时间
                        message.getMessageProperties().setDelay(10000);
                        //打印发送时间
                        System.out.println("发送时间===>"+sdf.format(new Date()));
                        //返回设置好的消息对象
                        return message;
                    }
                });
        return Result.ok();
    }
}
